<?php
/**
 * Easthv Zend Framework Project
 *
 *
 * LICENSE:
 *
 * @category   Zend
 * @package    Zend_Helper
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
*/

/**
 * Form Helper
 *
 * @category   Zend
 * @package    Zend_Helper
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
 * @deprecated
 */
class Zend_View_Helper_RestForm
{
    /**
     * @var object Zend_View
     */
    public $view;

    /**
     * @var string input name cache
     */
    private $_cacheName;

    /**
     * @var array input options cache
     */
    private $_cacheOptions;

    /**
     * @var mixed input HTML code cache
     */
	private $_cache;

    /**
     * @var boolean Zend_Locale Cache enabled flag
     */
	private $_l12nCacheInited = false;

    /**
     * Set Zend View
     *
     *
     * @param  Zend_View_Interface   $view   zend view interface 
     *
     * @access public
     *
     * @return void
     */
    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }


    /**
     * Render RESTFul form
     *
     *
     * @param  string $action   form action     
     * @param  string $method   form method  support  get|post|put|delete   
     * @param  array  $others   form others attribute   array('class'=>'test') will generate class="test"
     *
     * @access public
     *
     * @return string   RESTFul form HTML code
     */
    public function RestForm($action = null, $method = 'post', $others = '')
    {
        if (0 == func_num_args()) {
            return $this;
        }

        $hidden = '';
        $more = '';

        switch ($method)
        {
            case 'post':
                $method = 'post';
                break;
            case 'put' :
                $method = 'post';
                $hidden = '<input name="_method" type="hidden" value="PUT" />';
                break;
            case 'delete' :
                $method = 'post';
                $hidden = '<input name="_method" type="hidden" value="DELETE" />';
                break;
            default : 
                $method = 'get';
        }

        if ($others) {
            foreach($others as $key => $value) {
                $more .= $key . '="' . $value . '" ';
            }
        }

        $action = is_array($action) ? $this->view->Easy($action[0],$action[1]) : $this->view->Easy($action);

        return '<form action="' . $action . "\" method=\"$method\" $more > $hidden";
    }
    
    /**
     * Generates treeinput element or select options
     *
     * @param  string $name    input element name
     * @param  array  $options input attribute array    
     *
     * @access public
     *
     * @return string   input element HTML code
     */
    public function addNoneOption($options = null, $name = null)
    {

        if (!$name) {
            $name = 'None';
        }
        
        $name = $this->view->I18n($name);

        if (!$options || !is_array($options)) {
        
            $options = array('none'=>array("",$name));
        } else {
            
            $options = array('none'=>array("",$name)) + $options;     
        }
        return $options;

    }
    
    /**
     * Create form checkbox element
     * *
     * @param  string $name    input element name
     * @param  array  $options input attribute array
     *
     * @access public
     *
     * @return array  input element HTML code array
     *
     */
    public function checkbox($name = null, $options = null)
    {

        $options['type'] = 'checkbox';
        return $this->input($name,$options);
    
    }

    /**
     * Create form radio element
     * *
     * @param  string $name    input element name
     * @param  array  $options input attribute array
     *
     * @access public
     *
     * @return array  input element HTML code array
     *
     */
    public function radio($name = null, $options = null)
    {
        $options['type'] = 'radio';
        return $this->input($name,$options);    
    }

    /**
     * Create form select element
     * *
     * @param  string $name    input element name
     * @param  array  $options input attribute array
     *
     * @access public
     *
     * @return array  input element HTML code array
     *
     */
    public function select($name = null, $options = null)
    {
        $options['type'] = 'select';
        return $this->input($name,$options);    
    }

    /**
     * Create form input element
     * 
     * option setting:
     * array(
     *     'id' => string ,element id
     *     'class' => string ,element class
     *     'type' => string ,can be text | select | radio | checkbox , default is text , if there is options array , type will be change into select
     *     'options' => array , element key / value pairs
     *         if select , array('aaa','bbb') will tranform to <option value="aaa">bbb</option>
     *         if radio , array('aaa','bbb') will tranform to array( 'input' => <input type="radio" value="aaa" />  , label => bbb
     *         if checkbox , array('aaa','bbb') will tranform to array( 'input' => <input type="checkbox" value="aaa" />  , label => bbb
     *         if array length is more than 2, the third value will be as same as 'more'
     *         if array length is more than 3, the 4th value will be as additional array named 'data'
     *             'more' => array , if there are more attribute need to setting, setting key / value pairs here
     *                 example : array('tabindex' => 1) will tranform to tabindex="1"
     * ) 
     * @param  string $name    input element name
     * @param  array  $options input attribute array:
     *
     * @access public
     *
     * @return mixed  if input type is text or select, return input element HTML code string
     *                if input type is radio or checkbox, return input element HTML code array
     */
    public function input($name = null, $options = null)
    {
        //if input has been cache, return cache
        if ($this->_cacheName[$name] === $name && $this->_cacheOptions[$name] === $options) {
            return $this->_cache[$name];
        } else {
            $this->_cacheName[$name] = $name;
            $this->_cacheOptions[$name] = $options;
        }

        //prepare input attributes
        $_name = $name;
        $name = $name ? " name=\"$name\" " : null;
        $id = $options['id'] ? " id=\"{$options['id']}\"" : null;
        $class = $options['class'] ? " class=\"{$options['class']}\"" : null;
        $default = isset($options['default']) ? $options['default'] : null;
        $type = $options['type'] ? $options['type'] : (isset($options['options']) && is_array($options['options']) ? 'select' : 'text');
        
        $more = null;
        if (is_array($options['more'])) {
            foreach($options['more'] as $key => $value) {
                $more .= " $key =\"$value\" ";
            }        
        }

        $res = null;
        switch ($type) {

        case 'select' :

            $contents = '';
            if ($options['options']) {

                foreach($options['options'] as $option) {

                    if($default === null || $default != $option[0]) {
                        $contents .= '<option value="' . $option[0] . '">' .  $option[1] . '</option>';
                        continue;
                    }

                    $contents .= '<option value="' . $option[0] . '" selected="selected">' .  $option[1] . '</option>';

                }

            }
            
            $res = "<select $id $class $name $more>$contents</select>";

            break;

        case 'checkbox' :

            if(!$options['options']) {
                return array();
                //$res = "<input type=\"checkbox\" $name />";
                //break;
            }

            $res = array();

            //default value in checkbox must be an array
            $default = is_string($default) ? array($default) : $default;
    
            foreach($options['options'] as $option) {

                $add = null;
                if (is_array($option[2])) {
                    foreach($option[2] as $key => $value) {
                        $add .= " $key =\"$value\" ";
                    }        
                }

                if ($default === null || in_array($option[0],$default) === false) {

                    $res[] = array(
                        'input' => "<input type=\"checkbox\" $name value=\"{$option[0]}\" $class $add />",
                        'label' => $option[1],    
                        'data' => $option[3]
                    );
                    continue;
                }

                $res[] = array(
                    'input' => "<input type=\"checkbox\" $name value=\"{$option[0]}\" checked=\"checked\" $class  $add />",
                    'label' => $option[1],
                    'data' => $option[3]
                );
        

            }

            break;

        case 'radio' :

            if (!$options['options']) {
                return array();
                //$res = "<input type=\"radio\" $name />";
                //break;
            }
            $res = array();

            foreach($options['options'] as $option) {

                $add = null;
                if (is_array($option[2])) {
                    foreach($option[2] as $key => $value) {
                        $add .= " $key =\"$value\" ";
                    }        
                }
                if ($default === null || $default != $option[0]) {

                    $res[] = array(
                        'input' => "<input type=\"radio\" $name value=\"{$option[0]}\" $class $add />",
                        'label' => $option[1],    
                        'data' => $option[3]
                    );
                    continue;
                }

                $res[] = array(
                    'input' => "<input type=\"radio\" $name value=\"{$option[0]}\" checked=\"checked\" $class $add />",
                    'label' => $option[1],    
                    'data' => $option[3]
                );


            }

            break;

        default :
            $size = $options['size'] ? " size=\"{$options['size']}\" " : null;
            $res = $default === null ? "<input $id $class $size $name $more />" : "<input $id $class $size $name $more value=\"$default\" />";
        }
        
        return $this->_cache[$_name] = $res;
    }


    /**
     * Create Input Options Array by Zend_Locale
     *
     *
     * @param string $default default value
	 * @param array $priorityArray  some values need to put priority
     * @param  string $type Zend TranslationList type (see http://framework.zend.com/manual/en/zend.locale.functions.html)
     *
     * @access public
     *
     * @return void
     */
	public function opt($default, $priorityArray, $type, $lang = null)
	{

		if($this->view->config['cache']['enable'] && $this->view->config['cache']['l12n'] && false === $this->_l12nCacheInited) {
			Zend_Locale::setCache(Zend_Cache::factory('Core', 'File', array(
				'automatic_serialization' => true
			), $backendOptions = array(
                'cache_dir' => APPLICATION_PATH . $this->view->config['path']['cache']['l12n']
            )));
			$this->_l12nCacheInited = true;
		}

		$lang = $lang ? $lang : $this->view->language;
		$listen = Zend_Locale::getTranslationList($type, 'en');
		$list = Zend_Locale::getTranslationList($type, $lang);

		$opt = array();
		if($default) {
			$opt[] = $default;
		}

		if($priorityArray) {
			foreach($priorityArray as $priority)  {
				$opt[] = array($priority, $list[$priority]);
				unset($listen[$priority]);
			}
		}

		foreach($listen as $key => $value){
			if($list[$key]) {
				$opt[] = array($key, $list[$key]);
			} else {
				$opt[] = array($key, $value);
			}
		}
		return $opt;	
	}

	public function optCountries($default = null, $priorityArray = array('US'))
	{
		return $this->opt($default, $priorityArray, 'territory');
	}


	public function optLanguages($default = null, $priorityArray = array('en', 'zh', 'ja'), $skipSubLanguage = true, $noSkip = array('zh_Hant'))
	{
		$opt = $this->opt($default, $priorityArray, 'language');

		if(true === $skipSubLanguage) {
			foreach($opt as $key => $lang){
				if(false === strpos($lang[0], '_')) {
					continue;
				}

				if($noSkip && in_array($lang[0], $noSkip) === true) {
					continue;
				}
				unset($opt[$key]);
				
			}
		}

		return $opt;
	}

	public function optDays($default = null)
	{
		$days = array();
		if($default) {
			$days[] = $default;
		}

		for($i = 1; $i <=31; $i++){
			$days[] = array($i,$i);
		}

		return $days;
	
	}

	public function optMonths($default = null, $priorityArray = array())
	{
		return $this->opt($default, $priorityArray, 'month');
	}

	public function optYears($default = null, $plus = 150)
	{
		$years = array();
		if($default) {
			$years[] = $default;
		}

		$year = gmdate("Y", time());

		if($plus > 0){
			for($i = 0; $i <= $plus; $i++){
				$years[] = array($year - $i, $year - $i);
			}
		} else {
			for($i = 0; $i >= $plus; $i--){
				$years[] = array($year - $i, $year - $i);
			}
		}

		return $years;
	}
}
